﻿using Microsoft.EntityFrameworkCore;
using System;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Payment.Requests;

namespace Volo.Payment.EntityFrameworkCore
{
    public static class PaymentDbContextModelCreatingExtensions
	{
		public static void ConfigurePayment(this ModelBuilder builder, Action<PaymentModelBuilderConfigurationOptions> optionsAction = null)
		{
			Check.NotNull<ModelBuilder>(builder, nameof(builder));
			var options = new PaymentModelBuilderConfigurationOptions(PaymentDbProperties.DefaultDbTablePrefix, PaymentDbProperties.DefaultDbSchema);
			optionsAction?.Invoke(options);

			builder.Entity<PaymentRequest>(b =>
			{
				b.ToTable<PaymentRequest>(options.TablePrefix + "PaymentRequests", options.Schema);
				AbpEntityTypeBuilderExtensions.ConfigureByConvention(b);
				b.Property<PaymentRequestState>(x => x.State).IsRequired();
				b.Property<string>(x => x.FailReason);
				b.HasMany<PaymentRequestProduct>(x => x.Products)
					.WithOne()
					.HasForeignKey(x => x.PaymentRequestId);
				b.HasIndex(x => x.CreationTime);
			});
			builder.Entity<PaymentRequestProduct>(b =>
			{
				b.ToTable<PaymentRequestProduct>(options.TablePrefix + "PaymentRequestProducts", options.Schema);
				b.ConfigureByConvention();
				b.HasKey(x => new { x.PaymentRequestId, x.Code });
				b.HasOne<PaymentRequest>()
					.WithMany()
					.HasForeignKey(x => x.PaymentRequestId)
					.IsRequired();
				b.Property<string>(x => x.Code).IsRequired();
				b.Property<string>(x => x.Name).IsRequired();
				b.Property<float>(x => x.UnitPrice).IsRequired();
				b.Property<int>(x => x.Count).IsRequired();
				b.Property<float>(x => x.TotalPrice);
			});
		}
	}
}
